package com.fingard.dsp.bank.directbank.tjcb11;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.helpers.YBTHelper;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.net.FtpPortClient;
import com.fingard.net.FtpReceiver;
import com.fingard.net.SftpPortClient;
import com.fingard.text.StringHelper;

import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;
import java.text.MessageFormat;
import java.util.Date;

public class TJCB11BatPayRec extends TJCB11Base implements IBatPayRec {
    @Override
    public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
        return d_BatPayRec(p_req1988);
    }

    @Override
    public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
        return d_QryBatPayRec(p_req1998);
    }

    @Override
    public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
        return d_BatPayRec(p_req9188);
    }

    @Override
    public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
        return d_QryBatPayRec(p_req9198);
    }

    public RetAtsBatPayRec d_BatPayRec(ReqBatPayRec p_reqBat) throws Exception {
        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_reqBat.reqHeader);
        retAts.reqSeqID = p_reqBat.reqBatchNO;

        FtpPortClient ftpPortClient = null;

        try {
            Date tmpDateNow = getDayCutTime(p_reqBat.getPayDateTime());
            // 代收付文件内容
            StringBuilder sbFileContent = new StringBuilder();
            String totalNum = String.format("%6s", p_reqBat.totalNum).replace(" ", "0");
            String totalAmt = String.format("%15s", p_reqBat.totalAmt).replace(" ", "0");
            // 汇总信息：总笔数|文件总金额(单位:分)|数字签名串\n
            String tmpReqHeader = MessageFormat.format("{0}{1}", totalNum, totalAmt);
            sbFileContent.append(tmpReqHeader);
            String tempstr = "";
            String tmpDirType = "";
            if ("1998".equals(p_reqBat.reqHeader.transType)) {
                tempstr = "TJYH_YBTPLDF_";
                tmpDirType = "rec";
            } else {
                tempstr = "TJYH_YBTPLDS_";
                tmpDirType = "pay";
            }
            String tmpBatSeqNo = YBTHelper.getBatSeqNo(getTempFileDirectory(tmpDateNow) + File.separator + tmpDirType, 3);

            StringBuilder seqNoMappingContent = new StringBuilder();

            // 文件明细
            int seqNo = 0;
            while (p_reqBat.readRecord()) {
                if (sbFileContent.length() > 0) {
                    sbFileContent.append("\n");
                }
                if (seqNoMappingContent.length() > 0) {
                    seqNoMappingContent.append("\n");
                }
                String oppAct = "";
                String oppName = "";
                if ("1988".equals(p_reqBat.reqHeader.transType)) {
                    oppAct = String.format("%-18s", p_reqBat.readedDetail.recAct);
                    oppName = String.format("%-20s", p_reqBat.readedDetail.recName);
                } else {
                    oppAct = String.format("%-18s", p_reqBat.readedDetail.payAct);
                    oppName = String.format("%-20s", p_reqBat.readedDetail.payName);
                }
                String date = Format.Date8Format.format(new Date());
                String mark = "1F";
                String payAmt = p_reqBat.readedDetail.payAmount;
                if (payAmt.contains(".00")) {
                    payAmt = payAmt.replace(".00", "");
                }
                payAmt = String.format("%12s", payAmt).replace(" ", "0");

                String sourceNoteCode = String.format("%-30s", p_reqBat.readedDetail.sourceNoteCode);
                String batTransTypeFlag = p_reqBat.readedDetail.srcXElement.getSingleText(getBankConfig().getValueAsString("batTransType"));
                String batTransType = getBankConfig().getMapValueByKey("businessType"+p_reqBat.reqHeader.transType, batTransTypeFlag);
                String eachSeqNo = String.format("%12s", ++seqNo).replace(" ", "0");
                String tmpReqBodyDetail = MessageFormat.format("{0}{1}{2}{3}{4}{5}{6}{7}{8}", oppAct, oppName, date, mark, payAmt, eachSeqNo, date, sourceNoteCode, batTransType);
                sbFileContent.append(tmpReqBodyDetail);
                seqNoMappingContent.append(p_reqBat.readedDetail.askNumber).append(",").append(eachSeqNo);
            }
            WriteBankLogLn2("批次文件内容:\r\n" + sbFileContent.toString());

            String tmpPaySendDate = Format.Date8Format.format(tmpDateNow);
            String tmpUploadFileName = tempstr + bankFront.corpNo + "_" + tmpPaySendDate + "_" + tmpBatSeqNo;
            String tmpLocalMarkPath = getTempFileDirectory(tmpDateNow) + File.separator + tmpDirType + File.separator + tmpUploadFileName;
            WriteBankLogLn2("批次文件保存本机路径: " + tmpLocalMarkPath);

            if (FileHelper.existFile(tmpLocalMarkPath)) {
                retAts.respCode = "0";
                retAts.respInfo = "本地批次文件已上传,请勿重复上传!";
                retAts.reqSeqID = p_reqBat.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = FailCode.E9981;
                retAts.writeRetToATS();
                return retAts;
            }

            FileHelper.writeFile(tmpLocalMarkPath, sbFileContent.toString(), getCharset());
            // 批次流水映射存入本地
            WriteBankLogLn2("批次流水映射文件内容:\r\n" + seqNoMappingContent.toString());
            String tmpBatSeqNoFilePath = getDataFileDirectory(tmpDateNow) + File.separator + p_reqBat.reqBatchNO + "_" + tmpBatSeqNo + ".txt";
            WriteBankLogLn2("本地批次流水映射文件路径:" + tmpBatSeqNoFilePath);
            FileHelper.writeFile(tmpBatSeqNoFilePath, seqNoMappingContent.toString(), getCharset());

            // 上送银保通服务器
            FtpSet ftpSet = bankFront.getFtpSet("bat");
            ftpPortClient = new FtpPortClient(ftpSet);
            FtpReceiver ftpReceiver = ftpPortClient.uploadFile(tmpLocalMarkPath, tmpUploadFileName);

            retAts.respCode = "0";
            retAts.reqSeqID = p_reqBat.reqBatchNO;
            if (!ftpReceiver.isCompleted) {
                retAts.respCode = "-1";
                retAts.respInfo = ftpReceiver.connMsg;
            } else if (ConnState.FAIL.equals(ftpReceiver.connState)) {
                retAts.respInfo = "上传失败";
                retAts.transState = "BatchFailed";
                retAts.payInfoCode = "E9999";
            } else {
                retAts.respInfo = "上传成功";
                retAts.transState = "Uploaded";
                retAts.payInfoCode = "I4001";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        } finally {
            if (ftpPortClient != null) {
                ftpPortClient.disconnect();
            }
        }

        retAts.writeRetToATS();
        return retAts;
    }

    public RetAtsQryBatPayRec d_QryBatPayRec(ReqQryBatPayRec p_reqQryBat) throws Exception {
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_reqQryBat.reqHeader);
        retAts.reqSeqID = p_reqQryBat.reqBatchNO;

        FtpPortClient ftpPortClient = null;

        try {
            String tempstr = "";
            if ("1998".equals(p_reqQryBat.reqHeader.transType)) {
                tempstr = "TJYH_YBTPLDFHP_";
            } else {
                tempstr = "TJYH_YBTPLDSHP_";
            }
            Date tmpDateNow = getDayCutTime(p_reqQryBat.getBgnDateTime());
            String tmpPaySendDate = Format.Date8Format.format(tmpDateNow);
            // 1、读取本地批次流水映射文件
            File refundSeqNoDir = new File(getDataFileDirectory(tmpDateNow));
            if (refundSeqNoDir.exists()) {
                File[] refundSeqNoFileList = refundSeqNoDir.listFiles();
                boolean isMatched = false;
                for(File refundSeqNoFile : refundSeqNoFileList) {
                    if (refundSeqNoFile.getName().contains(p_reqQryBat.reqBatchNO)) {
                        isMatched = true;

                        String tmpSeqNoContent = FileHelper.readFileText(refundSeqNoFile.getAbsolutePath(), getCharset());
                        WriteBankLogLn2("本地批次流水映射文件内容:\r\n" + tmpSeqNoContent);
                        if (StringHelper.isNullOrEmpty(tmpSeqNoContent)) {
                            retAts.respCode = "-1";
                            retAts.respInfo = "批次流水映射文件内容为空!";
                            retAts.writeAfterDetail();
                            return retAts;
                        }
                        String[] tmpSeqNoArray = tmpSeqNoContent.split("\n");
                        String tmpBatNo = refundSeqNoFile.getName().replace(".txt", "").split("_")[1];
                        String tmpDownFileName = tempstr + bankFront.corpNo + "_" + tmpPaySendDate + "_" + tmpBatNo;
                        String tmpRecResultFilePath = getTempFileDirectory(tmpDateNow) + File.separator + tmpDownFileName;
                        WriteBankLogLn2("批次结果文件保存本地路径: " + tmpRecResultFilePath);

                        FtpSet ftpSet = bankFront.getFtpSet("bat");
                        ftpPortClient = new FtpPortClient(ftpSet);
                        FtpReceiver ftpReceiver = ftpPortClient.downloadFile(tmpDownFileName, tmpRecResultFilePath);
                        if (ftpReceiver.isCompleted) {
                            String tmpStrRet = FileHelper.readFileText(tmpRecResultFilePath, getCharset());
                            WriteBankLogLn2("本地批次结果文件内容:\r\n" + tmpStrRet);

                            if (StringHelper.hasAnyChar(tmpStrRet)) {
                                retAts.respCode = "0";
                                retAts.reqSeqID = p_reqQryBat.reqBatchNO;

                                StringReader strReader = new StringReader(tmpStrRet);
                                BufferedReader tmpReader = new BufferedReader(strReader);
                                tmpReader.readLine();

                                while (true) {
                                    String eachline = tmpReader.readLine();
                                    if (StringHelper.isNullOrEmpty(eachline)) {
                                        break;
                                    }
                                    if (eachline.length() == 115) {
                                        RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();

                                        for(String tmpSeqNo : tmpSeqNoArray) {
                                            WriteBankLogLn2("+++取的批次明细号"+tmpSeqNo);
                                            String seqNo = eachline.substring(60, 72).trim();
                                            if ((tmpSeqNo.length() > 0) && tmpSeqNo.split(",")[1].equals(seqNo)) {
                                                if (p_reqQryBat.reqHeader.transType.equals("1998")) {
                                                    tmpRetDetail.recAct = eachline.substring(0, 18).trim();
                                                    tmpRetDetail.recName = eachline.substring(18, 38).trim();
                                                } else if (p_reqQryBat.reqHeader.transType.equals("9198")) {
                                                    tmpRetDetail.payAct = eachline.substring(0, 18).trim();
                                                    tmpRetDetail.payName = eachline.substring(18, 38).trim();
                                                }
                                                tmpRetDetail.result = eachline.substring(46, 48).trim();
                                                tmpRetDetail.postScript = tmpSeqNo.split(",")[0];
                                                tmpRetDetail.payAmount = eachline.substring(48, 60).replaceAll("^(0+)", "");
                                                tmpRetDetail.payInfoCode = eachline.substring(80, 84);
                                                retAts.writeRetDetail(tmpRetDetail);
                                            }
                                        }
                                    } else {
                                        retAts.respCode = "-1";
                                        retAts.respInfo = "回盘文件明细长度不符，实际为：" + eachline.length();
                                    }
                                }
                            } else {
                                retAts.respCode = "-1";
                                retAts.respInfo = "回盘文件[" + tmpDownFileName + "]内容为空!";
                            }
                        } else {
                            retAts.respCode = "-1";
                            retAts.respInfo = "回盘文件下载失败:" + ftpReceiver.connMsg;
                        }
                    }
                }

                if (!isMatched) {
                    retAts.respCode = "-1";
                    retAts.respInfo = "本地批次流水映射目录不存在批次:" + p_reqQryBat.reqBatchNO + "流水映射文件!";
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "本地批次流水映射目录不存在，未发生过批量交易!";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        } finally {
            if (ftpPortClient != null) {
                ftpPortClient.disconnect();
            }
        }

        retAts.writeAfterDetail();
        return retAts;
    }
}